#!/bin/bash

# =====================================================
# 📚 公共函数库
# 路径：/usr/local/vpn/lib/vpn-common.sh
# 用法：source /usr/local/vpn/lib/vpn-common.sh
# =====================================================

# 统一配置路径
VPN_ROUTES_CONF="/usr/local/vpn/etc/vpn-routes.conf"
LOG_FILE="/usr/local/vpn/logs/vpn-script.log"
# 路由表备份文件
ROUTE_BACKUP_FILE="/usr/local/vpn/etc/vpn_route_backup.txt"

# 读取有效 CIDR（忽略注释、空行，支持行尾注释）
read_cidrs() {
    if [[ ! -f "$VPN_ROUTES_CONF" ]]; then
        echo "❌ 配置文件不存在: $VPN_ROUTES_CONF" >&2
        return 1
    fi

    grep -v '^[[:space:]]*#' "$VPN_ROUTES_CONF" | \
    grep -v '^[[:space:]]*$' | \
    awk '{print $1}' | \
    grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+$'
}

# 获取所有活跃的 tun/vpn 接口
get_vpn_interfaces() {
    ip link show 2>/dev/null | grep -E '^[0-9]+: (tun|vpn)[0-9]+:' | awk -F: '{print $2}' | tr -d ' ' | grep -v '^$' | sort -u
}